<template>
  <div class="repair-work-order-compoment">
    <div class="header-wrapper">
      <div class="header-title">报修工单管理</div>
      <div v-if="!props.isLook" class="header-btn" @click="addHandle">
        提交工单
      </div>
    </div>
    <div class="data-wrapper">
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          :border="true"
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="content" label="内容">
            <template #default="scope">
              <div class="content-wrapper">
                <img
                  src="@/assets/images/工单.png"
                  alt="内容"
                  class="content-logo"
                />
                <span class="content-text">{{ scope.row.content }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间">
            <template #default="scope">
              {{ formatDate(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template #default="scope">
              {{ formatDate(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="处理人">
            <template #default="scope">
              {{ scope.row.maintainerInfo.name }}
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <div :class="scope.row.status">
                {{ statusMap[scope.row.status as keyof typeof statusMap] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!props.isLook"
            label="操作"
            width="150"
            align="left"
          >
            <template #default="scope">
              <div
                v-if="false"
                class="table-btn"
                @click="editHandle(scope.row)"
              >
                编辑
              </div>
              <div class="table-btn" @click="deleteHandle(scope.row.id)">
                删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加报修工单"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="addForm.content"
            placeholder="请输入报修工单内容"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="addForm.startTime"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择报修工单开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="处理人" prop="maintainerCode">
          <el-select
            v-model="addForm.maintainerCode"
            placeholder="请选择处理人"
          >
            <el-option
              v-for="item in props.userList"
              :key="item.id"
              :label="item.name"
              :value="item.userCode"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, defineProps } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/assets/js/utils";
import {
  getRepairOrdersPageAPI,
  submitRepairOrderAPI,
  deleteRepairOrderAPI,
} from "@/api/service/repairWorkOrder";
import {
  RepairWorkOrderType,
  AddOrUpdateRepairWorkOrderQueryType,
  GetRepairOrdersPageType,
  RepairWorkOrderStatus,
} from "@/api/types/repairWorkOrder";
import { UserType } from "@/api/service/user";

const route = useRoute();
const deviceId = route.query.id as string;
const props = defineProps<{
  userList: UserType[];
  isLook?: boolean;
}>();

const statusMap = {
  IN_PROGRESS: "进行中",
  COMPLETED: "已完成",
};

// 表格数据
const queryParams = ref<GetRepairOrdersPageType>({
  page: 1,
  size: 10,
  deviceId: deviceId,
  maintainerCode: "",
  startTimeFrom: null,
  startTimeTo: null,
  status: RepairWorkOrderStatus.IN_PROGRESS,
});
const tableData = ref<RepairWorkOrderType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);
function getRepairWorkOrderList() {
  // 防止并发调用
  if (listApiLoading.value) return;
  listApiLoading.value = true;

  getRepairOrdersPageAPI({
    page: queryParams.value.page,
    size: queryParams.value.size,
    deviceId: queryParams.value.deviceId,
    maintainerCode: queryParams.value.maintainerCode,
    startTimeFrom: queryParams.value.startTimeFrom,
    startTimeTo: queryParams.value.startTimeTo,
    status: queryParams.value.status,
  })
    .then((_data: any) => {
      const data = _data.content as RepairWorkOrderType[];
      tableData.value = data;
    })
    .catch(() => {
      ElMessage.error("获取报修工单列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getRepairWorkOrderList();

// 添加报修工单
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
const addForm = ref<AddOrUpdateRepairWorkOrderQueryType>({
  content: "",
  deviceId: deviceId,
  startTime: null,
  maintainerCode: "",
  status: "",
});

function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑报修工单
function editHandle(row: RepairWorkOrderType) {
  addDialogVisible.value = true;
  addForm.value = {
    content: row.content,
    deviceId: row.deviceId,
    startTime: row.startTime,
    maintainerCode: row.maintainerCode,
    status: row.status,
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  content: [{ required: true, message: "请输入报修工单内容", trigger: "blur" }],
  startTime: [
    { required: true, message: "请选择报修工单开始时间", trigger: "blur" },
  ],
  maintainerCode: [
    { required: true, message: "请选择报修工单处理人", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择报修工单状态", trigger: "blur" }],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    content: "",
    deviceId: deviceId,
    startTime: null,
    maintainerCode: "",
    status: "",
  };
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;
      submitRepairOrderAPI({
        content: addForm.value.content,
        deviceId: addForm.value.deviceId,
        startTime: addForm.value.startTime,
        maintainerCode: addForm.value.maintainerCode,
        status: addForm.value.status || "IN_PROGRESS",
      })
        .then(() => {
          ElMessage.success(
            addForm.value.id ? "编辑报修工单成功" : "添加报修工单成功"
          );
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          getRepairWorkOrderList();
        })
        .catch(({ message }) => {
          ElMessage.error(message);
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}

// 删除报修工单
function deleteHandle(id: string) {
  ElMessageBox.confirm("确定删除该报修工单吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteRepairOrderAPI(id)
      .then(() => {
        ElMessage.success("删除报修工单成功");
        getRepairWorkOrderList();
      })
      .catch(() => {
        ElMessage.error("删除报修工单失败");
      });
  });
}
</script>

<style scoped lang="scss">
.repair-work-order-compoment {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem;
  background-color: $bg-color-page;
  border-bottom: 1px solid $border-color-primary;
  .header-title {
    font-size: $font-size-page-menu;
    font-weight: 600;
    color: $text-color-regular;
    padding-left: 12px;
    border-left: 4px solid $color_brand;
  }
  .header-btn {
    display: inline-flex;
    align-items: center;
    color: $text-color-regular;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    background: $bg-td-2-color;
    padding: 0.2rem 1rem;
    border-radius: 0.5rem;
  }
  .header-btn:hover {
    text-decoration: underline;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    padding: 0 0;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    color: $text-color-regular;
    margin-left: 1rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .IN_PROGRESS {
    color: $color_danger;
  }
  .COMPLETED {
    color: $color_success;
  }
  .content-wrapper {
    display: flex;
    align-items: center;
    .content-logo {
      width: 2rem;
      height: 2rem;
      margin-right: 1rem;
    }
  }
  .content-text {
    font-size: $font-size-base-btn-text;
    color: $text-color-primary;
  }
}
</style>
